package com.hn.zhijian.web.config.shiro;

import com.hn.zhijian.base.common.exception.ApplicationException;
import com.hn.zhijian.utils.Utils;
import com.hn.zhijian.web.config.jwt.JwtDefaultSubjectFactory;
import com.hn.zhijian.web.config.jwt.JwtFilter;
import lombok.Data;
import lombok.Setter;
import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SessionStorageEvaluator;
import org.apache.shiro.mgt.SubjectFactory;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.AnonymousFilter;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSessionStorageEvaluator;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.*;

/**
 * @program: carl-main
 * @description: shiro配置
 * @author: carl
 * @create: 2019-12-06 23:20
 **/
@Configuration
@ConfigurationProperties(prefix = "shiro-intercept")
@Data
public class ShiroConfiguraction {

    /**
     * 不要拦截的链接
     */
    private String anon;

    /**
     * 拦截URL
     */
    private String authc;

    @Bean
    public Realm realm() {
        return new UserAuthRealm();
    }


//    @Bean
//    protected CacheManager cacheManager() {
//        return new MemoryConstrainedCacheManager();
//    }

    @Bean
    public Authorizer authorizer() {
        return new ModularRealmAuthorizer();
    }


    @Bean
    public SubjectFactory subjectFactory() {
        return new JwtDefaultSubjectFactory();
    }


    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm());
        // 关闭 ShiroDAO 功能
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        // 不需要将 Shiro Session 中的东西存到任何地方（包括 Http Session 中）
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        securityManager.setSubjectDAO(subjectDAO);
        //禁止Subject的getSession方法
        securityManager.setSubjectFactory(subjectFactory());
        return securityManager;
    }

    /**
     * 加载控制
     *
     * @return
     */
    @Bean
    public AuthenticatingFilter authenticatingFilter() {
        return new JwtFilter();
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager());
//        shiroFilter.setLoginUrl("/unauthenticated");
//        shiroFilter.setUnauthorizedUrl("/unauthorized");
        /*
         * c. 添加jwt过滤器，并在下面注册
         * 也就是将jwtFilter注册到shiro的Filter中
         * 指定除了login和logout之外的请求都先经过jwtFilter
         * */
                // 拦截器
        Map<String, String> filterRuleMap = new LinkedHashMap<>();
//        filterRuleMap.put("/login", "anon");
//        filterRuleMap.put("/logout", "logout");
//        filterRuleMap.put("/user/login", "anon");
//        filterRuleMap.put("/account/login", "anon");
//        filterRuleMap.put("/test/**", "anon");
//        filterRuleMap.put("/**", "authc");
        filterRuleMap.putAll(getAnon());
        Map<String, Filter> filterMap = new HashMap<>();
        //这个地方其实另外两个filter可以不设置，默认就是
        filterMap.put("authc", new JwtFilter());
        shiroFilter.setFilters(filterMap);
        filterRuleMap.putAll(getAuthc());
        shiroFilter.setFilterChainDefinitionMap(filterRuleMap);
        return shiroFilter;
    }



    /**
     * 禁用session, 不保存用户登录状态。保证每次请求都重新认证。
     * 需要注意的是，如果用户代码里调用Subject.getSession()还是可以用session，如果要完全禁用，要配合下面的noSessionCreation的Filter来实现
     */
    @Bean
    protected SessionStorageEvaluator sessionStorageEvaluator() {
        DefaultWebSessionStorageEvaluator sessionStorageEvaluator = new DefaultWebSessionStorageEvaluator();
        sessionStorageEvaluator.setSessionStorageEnabled(false);
        return sessionStorageEvaluator;
    }

    private LinkedHashMap<String,String> getAnon(){
        LinkedHashMap<String,String>  map = new LinkedHashMap<>(10);;
        if(Utils.isEmpty(anon)){
            return map;
        }else{
            List<String> anonList= Arrays.asList(anon.split(","));
            for(String key : anonList){
                map.put(key,"anon");
            }
        }
        return map;
    }


    private LinkedHashMap<String,String> getAuthc(){
        LinkedHashMap<String,String> map = new LinkedHashMap<>(10);
        if(Utils.isEmpty(authc)){
            return map;
        }else{
            List<String> anonList= Arrays.asList(authc.split(","));
            for(String key : anonList){
                map.put(key,"authc");
            }
        }
        return map;
    }
}
